package com.whynot.frame.manythread.producerandcusumer.product;

import java.util.concurrent.BlockingDeque;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

import com.whynot.frame.manythread.producerandcusumer.entities.Data;

public class Product implements Runnable{
	
	private volatile boolean isRunning = true;//保存多个线程去读取改变量的时候，是从从内存中获取
	
	private BlockingDeque<Data> qeque ;//BlockingDeque是锁和堵塞实现的线程同步，所以在高并发场景效果不是很好
	
	private static AtomicInteger count = new AtomicInteger();//原子操作，保证多个线程访问的数据也不重复
	
	
	public Product(BlockingDeque<Data> qeque) {
		super();
		this.qeque = qeque;
	}


	public void run() {
		Data data = null;
		System.out.println("生产者的当前线程Id:"+Thread.currentThread().getId());
		try {
			Thread.sleep(1000);
		
			while(isRunning){
				data = new Data();
				data.setData(count.incrementAndGet());
				System.out.println("插入的数据:"+data);
				if(!qeque.offer(data,2,TimeUnit.SECONDS)){//2秒中还无法把数据插入，就返回false
					System.out.println("缓冲队列已满，暂时无法加入数据:"+data);
				}
			}
		} catch (InterruptedException e) {
			Thread.currentThread().interrupted();
			e.printStackTrace();
		}
	}
	
	
	public void stop(){
		isRunning = false;
	}
	

}
